package com.ibuonline.search.solr.dict;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public abstract class AbstractDictDetector implements DictDetector {

	/**
	 * 词条最小长度
	 */
	protected int minLength = DEFAULT_TERM_MIN_LENGTH;
	/**
	 * 词条最大长度
	 */
	protected int maxLength = DEFAULT_TERM_MAX_LENGTH;
	/**
	 * 词库刷新模式，日模式或时模式，缺省为日模式
	 */
	private RefreshMode refreshMode = RefreshMode.DAY;
	private Timer timer;

	public AbstractDictDetector() {
		super();
	}

	@Override
	public void setMinLength(int minLength) {
		if (minLength < 2) {
			throw new IllegalArgumentException("Negative minLength.");
		}
		this.minLength = minLength;
	}

	@Override
	public void setMaxLength(int maxLength) {
		if (maxLength < this.minLength) {
			throw new IllegalArgumentException("Negative maxLength.");
		}
		this.maxLength = maxLength;
	}

	@Override
	public void setRefreshMode(RefreshMode refreshMode) {
		this.refreshMode = refreshMode;
	}

	@Override
	public void start() {
		if (RefreshMode.DAY.equals(refreshMode)) {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_YEAR, 1);
			calendar.set(Calendar.HOUR_OF_DAY, 00);
			calendar.set(Calendar.MINUTE, 00);
			calendar.set(Calendar.SECOND, 00);
			timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					loadDict();
				}

			}, calendar.getTime(), DAY);
		}
		if (RefreshMode.HOUR.equals(refreshMode)) {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.HOUR_OF_DAY, 1);
			calendar.set(Calendar.MINUTE, 00);
			calendar.set(Calendar.SECOND, 00);
			timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					loadDict();
				}

			}, calendar.getTime(), HOUR);
		}
	}

	@Override
	public void stop() {
		if (this.timer != null) {
			this.timer.cancel();
			this.timer = null;
		}
	}

	public abstract void loadDict();
}